package com.ramble.zxing;



import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * 对城管加密 AES
 */
public class AESUtils {

    /**
     * 算法名称
     */
    private static final String AES_ALGORITHM = "AES";

    /**
     * 默认密钥长度
     */
    private static final Integer DEFAULT_KEY_SIZE = 128;

    //参数分别代表 算法名称/加密模式/数据填充方式
    private static final String ALGORITHM_STR = "AES/ECB/PKCS5Padding";

    /**
     * 加密
     *
     * @param content    加密的字符串
     * @param encryptKey key值
     * @return
     * @throws Exception
     */
    public static String encrypt(String content, String encryptKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), AES_ALGORITHM));
        byte[] b = cipher.doFinal(content.getBytes(CommonUtils.CHARSET));
        // 采用base64算法进行转码,避免出现中文乱码
        return Base64.encodeBase64URLSafeString(b);

    }

    public static String encrypt(String content, byte[] encryptKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey, AES_ALGORITHM));
        byte[] b = cipher.doFinal(content.getBytes(CommonUtils.CHARSET));
        // 采用base64算法进行转码,避免出现中文乱码
        return Base64.encodeBase64URLSafeString(b);

    }

    /**
     * 解密
     *
     * @param encryptStr 解密的字符串
     * @param decryptKey 解密的key值
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptStr, String decryptKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), AES_ALGORITHM));
        // 采用base64算法进行转码,避免出现中文乱码
        byte[] encryptBytes = Base64.decodeBase64(encryptStr);
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }
}
